package com.petcommunity.servlet;

import com.petcommunity.dao.LostPetDAO;
import com.petcommunity.model.LostPet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.sql.Date;

@WebServlet("/lostpets")
public class LostPetServlet extends HttpServlet {

    private LostPetDAO lostPetDAO = new LostPetDAO();

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<LostPet> lostPets = lostPetDAO.getAllLostPets();
        request.setAttribute("lostPets", lostPets);
        request.getRequestDispatcher("lostpets.jsp").forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的字符编码为 UTF-8
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        try {
            LostPet lostPet = new LostPet();
            lostPet.setPetId(Integer.parseInt(request.getParameter("petId")));
            java.util.Date utilDate = new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("lostDate"));
            lostPet.setLostDate(new java.sql.Date(utilDate.getTime()));
            lostPet.setLocation(request.getParameter("location"));
            lostPet.setDescription(request.getParameter("description"));
            lostPet.setFound(Boolean.parseBoolean(request.getParameter("found")));

            lostPetDAO.addLostPet(lostPet);
            response.sendRedirect("lostpets");
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("error.jsp");
        }
    }
}

